<template>
  <div class="citylist">
    <div>
      <div class="toptitle">
        <div class="top-left-search">
          <van-search v-model="taskListName" show-action placeholder="请输入任务名称" @search="serachData">
            <template #left>
              <!--{{options}}-->
              <div @click="options.length>0?show2 = true:''" style="margin-right: 5px;font-size: 14px;">
                <van-icon name="arrow-down" />{{areaValue }}</div>
            </template>
            <template #action>
              <div style="display: flex;align-items: center;">
                <!--<span @click="serachData" style="margin-right: 5px;">搜索</span>-->
                <van-button @click="changeMap" type="info" size="small"><van-icon name="exchange" />地图</van-button>
              </div>
            </template>
          </van-search>
          <!--<van-search   show-action background="#eee" v-model="taskListName" placeholder="请输入搜索关键词" @search="serachData" >-->
            <!--<template #action>-->
              <!--<div @click="changeMap">-->
                <!--<van-icon name="exchange" size="18" />-->
                <!--地图-->
              <!--</div>-->
            <!--</template>-->
          <!--</van-search>-->
        </div>
      </div>
      <div class="middle" style="overflow: auto;">
        <div class="search-list">
          <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
            <div class="search-list-top" v-for="(item, index) in cityName" :key="index" @click="toDetails(item)">
              <div class="top">
                <div style="float: left;"><span style="font-weight:1000; font-size: 18px;color: #000;line-height: 36px;">{{item.name}}</span></div>
              </div>
              <div class="top1">
                行政区划：<span style="font-weight: 500;">
                {{ item.provinceName?item.provinceName:''}}
                {{item.cityName?item.cityName:''}}
                {{item.countryName?item.countryName:''}}
              </span>
              </div>
              <div class="top1">
                任务创建时间：<span style="font-weight: 500;">{{item.createDate}}</span>
              </div>
              <div class="top">
                <div style="float:left;">
                  任务类型：<span style="font-weight: 500;">{{ item.type==1?'日常检查':'专项检查' }}</span>
                </div>

              </div>
              <div class="top" style="clear:both;">
                <div >
                  已检查：<span style="font-weight: 500;">{{ item.checkedNum}}</span>
                </div>
              </div>

            </div>
          </van-list>
        </div>
      </div>
      <div class="bottom">
        <div class="bottom-top">
          <van-button style="width: 100vw;" type="info" @click="creatingTasks">创建任务</van-button>
        </div>
      </div>
    </div>
    <van-popup v-model="show2" @click-overlay="closePopup" round position="bottom">
      <!--@finish="onFinish"-->
      <van-cascader v-model="cityCode" title="请选择" :closeable="false" :options="options" @change="onChange"
                    @confirm="closePopup"    />
      <!--@close="closePopup"-->
      <span style="position: absolute; top: 2%; right: 10px;font-size: 16px;" @click="closePopup">确定</span>

    </van-popup>
  </div>
</template>
<script>
import { houseCheckSupervisionFwCheckList1,houseCheckFwCheckList,FileServerProxy ,GetAdministrative,getDatalistForTree} from '../../../utils/api'
import dd from 'gdt-jsapi'
import axios from 'axios'

export default {
  data() {
    return {
      codeLevel:'',
      cityCode:'',
      options:[],
      areaValue:'',
      show2:false,
      finished2:false,
      loading2:false,
      formData:{
        province:'惠州市',
        finishDate:'',
        name:'',
        cityCode:'',
        type:2
      },
      cityName2:[],
      BaseURL:window.g.BaseURL,
      taskListName:'',
      totalCount:0,
      nowIndex:0,
      bottomList: ['待检查', '已检查'],
      showList:false,
      rowData:{

      },
      fileList2: [
        {
          name: '任务名称',
          type:'input',
          key:'name'
        },
        {
          title: '任务区域'
        },
        {
          name: '省（市、区）',
          type:'input',
          readonly:true,
          key:'province',
        },
        {
          name: '市（州、盟）',
          type:'select',
          key:'a',
          showPicker:false,
          columns:[],
          level:'市',
          required:true
        },
        {
          name: '县（市、区、旗）',
          type:'select',
          key:'b',
          columns:[],
          showPicker:false,
          level:'县',
          required:true
        },
        {
          name: '乡（镇、街道）',
          type:'select',
          key:'c',
          columns:[],
          showPicker:false,
          level:'村镇',
        },
        {
          name: '村（社区）',
          type:'select',
          key:'d',
          columns:[],
          showPicker:false,
          level:'社区'
        },
        {
          name: '计划完成时间',
          type:'time',
          key:'finishDate',
          showPicker:false,
        },
      ],
      showAdd:false,
      loading: false,
      finished: false,
      list:[],
      value:'',
      showPicker:false,
      sortList: [
        {
          title: '所属区域',
          name: 'RWZT',
          sort: 'asc'
        },
      ],
      value1: 0,
      option1: [
        { text: '全部商品', value: 0 },
        { text: '新款商品', value: 1 },
        { text: '活动商品', value: 2 },
      ],
      //省市区
      SXQ: '',
      ISshow:false,
      cityName: [],
      //区分当前点击的是市区县
      isCity: 0,
      XZQHName: '',
      CountyData:[],
      pageNum:0
    }
  },
  methods: {
    creatingTasks(){
      this.$router.push({
        path: '/homeInspectionAdd',
      })
    },
    getXZQH: async function (value, selectedOptions, tabIndex) {
      var res = await GetAdministrative(value)
      selectedOptions[tabIndex].children = []
      if (res.data.data.length > 0) {
        res.data.data.forEach((element) => {
          let obj = {
            text: element.cityname,
            value: element.citycode
          }
          if (tabIndex < 1) {
            obj['children'] = []
          }
          selectedOptions[tabIndex].children.push(obj)
        })
      }
    },
    onChange({ value, selectedOptions, tabIndex }) {
      if (selectedOptions[tabIndex].children && selectedOptions[tabIndex].children.length == 0 && tabIndex < 2) {
        this.getXZQH(value, selectedOptions, tabIndex)
      }
      this.onFinish({value, selectedOptions, tabIndex})
    },
    onFinish({value, selectedOptions, tabIndex} ) {
      if (selectedOptions[selectedOptions.length-1].text) {
        this.areaValue = selectedOptions[selectedOptions.length-1].text;
      } else {
        this.getCityName(window.localStorage.getItem('citycode'))
      }
      // this.areaValue = selectedOptions.at(-1).text;
      this.cityCode = value

      // this.form.cityCode.length == 3 ? (this.IsShowAre = false) : ''
    },
    getXianOpenDataView: async function (data) {
      this.options = [{
        text: window.localStorage.getItem('cityName'),
        value: window.localStorage.getItem('citycode'),
      }]
      const res = await getDatalistForTree(data)
      res.data.data.forEach((item) => {
        this.options.push({
          text: item.cityname,
          value: item.citycode,
          children: []
        })
      })
      // this.options = res.data.data
    },
    closePopup() {
      // alert()
      this.finished = false;
      this.pageNum = 1
      this.cityName = []
      this.show2 = false;
      this.getData()
      // this.getcontentData()
    },
    toDetails(item){
      // console.log(item)
      // if (item.type==1) {
        localStorage.removeItem("listCityCode")
        localStorage.removeItem("options")
      // }
      this.$router.push({
        path: '/homeInspectionlist',
        query: {
          data: JSON.stringify(item),
        },
      })
    },
    getList: async function (item){
      this.getListItem = item
      let param = {
        "cityCode": item.queryCityCode,  // 当前行的queryCityCode，必传
        "taskId": item.id,  // 必传
        "taskStatus": this.nowIndex,  // 检查状态，必传
        "pageNum": 1,
        "pageSize": 100
      }
      let result = await axios.post(`${this.BaseURL}api/farmerHouse/houseCheckFwCheckCountry/list`, param);
      if (result.data && result.data.data) {
        this.totalCount = result.data.data.totalCount
        this.cityName2 = result.data.data.pageList
        this.finished2 = true;
      }
    },
    confirmBtn: async function (){

      if (this.formData.cityCode && this.formData.name) {
        let param = {
          "cityCode": this.formData.cityCode,
          "name": this.formData.name,
          "finishDate":this.formData.finishDate?this.formData.finishDate+' 00:00:00':'',
          "type":this.formData.type
        }
        let result = await axios.post(`${this.BaseURL}api/farmerHouse/houseCheckFwCheckCountry/taskSave`, param);
        if (result.data.data){
          this.$toast.success("保存成功")
          this.showAdd = false
          this.getData()
        }
      } else {
        this.$toast.fail("请填写必填项")
      }

    },
    toHomeInspection(){
      this.$router.push({
        path: '/homeInspection',
      })
    },
    onSearch(){

    },
    bottomListBtn(item, index) {
      this.totalCount = ""
      this.nowIndex = index
      this.getList(this.getListItem)
    },
    // onChange(picker, values){
    //   console.log(picker, values)
    // },
    onConfirm2(data,item){
      this.formData[item.key] = data.cityname
      if (item.name=='市（州、盟）') {
        this.getCityData(data.citycode).then((webResult)=>{
          this.fileList2[4].columns = webResult.data.data
        })
      } else  if (item.name=='县（市、区、旗）') {
        this.getCityData(data.citycode).then((webResult)=>{
          this.fileList2[5].columns = webResult.data.data
        })
      }else  if (item.name=='乡（镇、街道）') {
        this.getCityData(data.citycode).then((webResult)=>{
          this.fileList2[6].columns = webResult.data.data
        })
      }
      this.formData.cityCode = data.citycode
      item.showPicker = false
    },
    async onLoad() {
      this.pageNum += 1
      this.getData()
    },
    //获取当前施工负责人列表
    async getData() {
      let param = {
        "cityCode": this.cityCode?this.cityCode:window.localStorage.getItem('citycode'),
        "name": this.taskListName,
        "pageNum": this.pageNum,
        "pageSize": 10
      }
      let result = await axios.post(`${this.BaseURL}api/farmerHouse/houseCheckFwCheckCountry/taskList`, param);
      if (result.data && result.data.data.pageList.length>0) {
        result.data.data.pageList.forEach((item,index)=>{
          this.cityName.push(item)
        })
        this.loading = false;
        if (this.cityName.length==result.data.data.totalCount) {
          this.finished = true;
        }else {
          this.finished = false;
        }
      } else {
        // this.cityName = []
        this.loading = false;
        this.finished = true;
      }
      // let data = {
      //   "accessCode": "688bd3883572440a859dfd8ba9194e7b",
      //   "cityCode": window.localStorage.getItem('citycode'),
      //   "params": {
      //     "dataguid": "88e8c4b2-7f4e-4a12-ae99-26233e202274",
      //     "searchObject": "",
      //     "token": window.localStorage.getItem('token')
      //   }
      // }
      // const res = await FileServerProxy(data)
      // this.cityName = this.list.concat(JSON.parse(res.data.data).Data);
      // this.finished = true;
    },
    changeMap(){
      this.$router.push({
        path: '/HouseExamination',
        query: {
          citycode: window.localStorage.getItem('citycode'),
          cityname: this.areaValue,
        },
      })
    },
    serachData(val) {
      this.pageNum = 0
      this.finished = true
      this.cityName = []
      this.onLoad()
      // this.getData()
      // if (!val) return this.list = this.deepListData
      // this.list = this.list.filter(item => {
      //   return item.XCR && item.XCR.indexOf(val) > -1
      // })

    },
    onConfirm(val) {
      if (val.cityname == '') {
        this.sortList[0].title = '所属区域'
      } else {
        this.sortList[0].title = val.cityname
        this.cityCode = val.citycode
      }
      this.showPicker = false
      this.startPage = 0
      this.ListDataOption = []
      this.onLoad()
    },
    //字段排序
    _sortlichange(item, index) {
      const self = this
      if (item.sort == 'asc') {
        item.sort = 'desc'
      } else {
        item.sort = 'asc'
      }
      if (index == 0) {
        this.showPicker = true
        this.showPicker1 = false
      } else {
        this.showPicker1 = true
        this.showPicker = false
      }
    },
    getCountyData: async function () {
      // this.CountyData = []
      // let webResult = await axios.get(window.g.BaseURL + 'api/rescatalog/gsaCodeCity/listForTree/' + window.localStorage.getItem('citycode'))
      // this.CountyData = webResult.data.data
      this.getCityData(window.localStorage.getItem('citycode')).then((webResult)=>{
        this.CountyData = webResult.data.data
        if (this.codeLevel=='市') {
          this.fileList2[4].columns = webResult.data.data
        } else if (this.codeLevel=='县') {
          this.fileList2[5].columns = webResult.data.data
        }else if (this.codeLevel=='村镇') {
          this.fileList2[6].columns = webResult.data.data
        }
      })
    },
    //根据citycode区分市区县镇街道
    discriminateCity(str) {
      debugger
      if (str.endsWith('0000000000')) {
        //省
        this.isCity = 0
      } else if (str.endsWith('00000000')) {
        //市
        this.isCity = 1
      } else if (str.endsWith('000000')) {
        //区
        debugger
        this.isCity = 2
      } else if (str.endsWith('000')) {
        //街道
        this.isCity = 3
        this.ISshow = false
      } else {
        //村
        this.isCity = -1
        this.ISshow = false
      }
    },
    handlegoto(data) {
      this.$router.push({
        path: '/SinceBuilding',
        query: {
          data: data.cityCode,
        },
      })
    },
    SelectGoto: async function (data) {
      this.$router.push({
        path: '/SinceBuildings',
        query: {
          data: JSON.stringify(data),
          type:'map'
        },
      })
      // let parmes = {
      //   cityCode: data.cityCode,
      //   houseUse: 6,
      //   masterName: '',
      //   pageNo: 0,
      //   pageSize: 0,
      //   roleType: window.sessionStorage.getItem('citycodeRole'),
      // }
      // if (data.cityCode.length < 12 ||(data.cityCode.length  == 12 && data.cityCode.endsWith('000'))) {
      //   if (
      //     window.sessionStorage.getItem('citycodeRole') == '0' &&
      //     window.sessionStorage.getItem('SelectCity') == '1'
      //   ) {
      //     parmes.roleType = 1
      //   } else if (
      //     window.sessionStorage.getItem('citycodeRole') == '0' &&
      //     window.sessionStorage.getItem('SelectCity') == '2'
      //   ) {
      //     parmes.roleType = 2
      //   } else if (
      //     window.sessionStorage.getItem('citycodeRole') == '1' &&
      //     window.sessionStorage.getItem('SelectCity') == '2'
      //   ) {
      //     parmes.roleType = 2
      //   }
      //   const res = await houseCheckSupervisionFwCheckList1(parmes)
      //   this.cityName = res.data.data
      //   console.log(data,'xiaohe')
      //   console.log(window.sessionStorage.getItem('citycodeQXName'), 'kkkk')
      //   this.XZQHName = this.XZQHName + '  ' + data.cityName
      // } else {
      //   //选中了村 前去填表单
      //   this.ISshow = false
      //   this.XZQHName = this.XZQHName + '  ' + data.cityName
      //   window.sessionStorage.setItem('citycodeQXName1', this.XZQHName)
      //   window.sessionStorage.setItem('citycodeCun', data.cityCode)
      //   this.$router.push({
      //     path: '/SinceBuilding',
      //     query: {
      //       data: data.cityCode,
      //     },
      //   })
      // }
    },
    handleSelectL: async function () {
      let parmes = {
        cityCode: window.sessionStorage.getItem('citycodeQX'),
        houseUse: 6,
        masterName: '',
        pageNo: 1,
        pageSize: 10000,
        roleType: window.sessionStorage.getItem('citycodeRole'),
      }
      if (window.sessionStorage.getItem('citycodeRole') == '0' && window.sessionStorage.getItem('SelectCity') == '1') {
        parmes.roleType = 1
      } else if (
        window.sessionStorage.getItem('citycodeRole') == '0' &&
        window.sessionStorage.getItem('SelectCity') == '2'
      ) {
        parmes.roleType = 2
      } else if (
        window.sessionStorage.getItem('citycodeRole') == '1' &&
        window.sessionStorage.getItem('SelectCity') == '2'
      ) {
        parmes.roleType = 2
      }
      const res = await houseCheckSupervisionFwCheckList1(parmes)
      this.cityName = res.data.data
      this.XZQHName = window.sessionStorage.getItem('citycodeQXName')
    },
    getCityData: async function (data){
      return new Promise(async(resovlve, reject) => {
         let webResult = await axios.get(window.g.BaseURL + 'api/rescatalog/gsaCodeCity/listForTree/' + data)
          resovlve(webResult)
      })
    },
    onConfirm3(date,item){
      this.formData[item.key] = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
      item.showPicker = false;
    },
    //判断省市||区县
    citycode(str) {
      if (str.endsWith("0000000000")) {
        //省
        return "省";
      } else if (str.endsWith("00000000")) {
        return "市";
      } else if (str.endsWith("000000")) {
        return "县";
      } else if (str.endsWith("000")) {
        return "村镇";
      } else {
        return "社区"
      }
    },
    getCityName: async function (code){
      let result = await axios.post(`${this.BaseURL}api/farmerHouse/cityCode/getAllParentByCityCode?cityCode=${code}`);
      // this.areaValue = result.data.data.cityName
      if (result.data.data.provinceName) {
        this.areaValue = result.data.data.provinceName
      }
      if (result.data.data.cityName) {
        this.areaValue = result.data.data.cityName
      }
      if (result.data.data.countyName) {
        this.areaValue = result.data.data.countyName
      }
      if (result.data.data.townName) {
        this.areaValue = result.data.data.townName
      }
      if (result.data.data.villageName) {
        this.areaValue = result.data.data.villageName
      }
    }
  },
  mounted() {
    this.codeLevel = this.citycode(window.localStorage.getItem('citycode'))
    this.getCityName(window.localStorage.getItem('citycode'))
    this.getXianOpenDataView(window.localStorage.getItem('citycode') ? window.localStorage.getItem('citycode') : "330000000000")
    // this.getData()
    this.getCountyData()
    this.SXQ = this.$route.query.data
    // this.handleSelectL()
    //根据路由传递的data和citycode动态切换列表数据
    dd.ready(function () {
      dd.setTitle({
        title: "房屋检查",
      })
        .then((res) => {})
        .catch((err) => {
          console.error(err)
        })
    })
  },
}
</script>

<style lang="scss" scoped>
.citylist {
  /*font-size: 14px;*/
  height: 100vh;
  width: 100vw;
  font-family: "Helvetica Neue", Helvetica, STHeiTi, sans-serif;
  background-color: #eee;
  overflow-y: auto;
  .bottomfix {
    border-radius: 10px;
    // height: 5vh;
    background: #fff;
    color: #000 !important;
    margin: 10px 0px;
    .secelt {
      background: #1989fa;
      border-radius: 10px;
      // border-top-left-radius: 10px;
      // border-bottom-left-radius: ;
    }
  }
  .subTitle {
    width: 100%;
    height: 40px;
    line-height: 40px;
    font-size: 14px;
    position: relative;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #9b9b9b;
    padding-left: 10px;

    .line {
      width: 6px;
      height: 26px;
      background: #3f8ffc;
      display: inline-block;
      margin-right: 10px;
    }
  }
  .middle1 {
    height: 87vh;
    overflow-y: auto !important;
    font-weight:400;
  }
  .sort {
    height: 5vh;
    line-height: 5vh;
    background: #fff;
    ul {
      display: flex;
      li {
        // width: 33.33333333333%;
        width: 100%;
        text-align: center;
        font-size: 1.6vh;
        font-weight: 400;
        color: #6c6c6c;
        cursor: pointer;
        img {
          height: 1.5vh;
        }
      }
    }
  }
  .middle {
    padding: 10px;
    background: #ffffff;
    .search-list {
      height: 83vh;
      .search-list-top {
        overflow: auto;
        background-color: #fff;
        /*border-radius: 8px;*/
        border-bottom: 1px solid #ebedf0;
        padding: 8px;
        // box-shadow: 0 3px 3px rgba(0, 0, 0, 0.2);
        margin-bottom: 8px;

        .top {
          /*display: flex;*/
          /*justify-content: space-between;*/
          line-height: 24px;
          color: #aaa;
          font-size: 14px
        }

        .top1 {
          /*display: flex;*/
          /*justify-content: space-between;*/
          line-height: 24px;
          clear: both;
          color: #aaa;
          font-size: 14px
        }

        .bottom {
          display: flex;
          justify-content: space-between;
          line-height: 24px;
        }
      }
    }
  }
  .toptitle {
    /*display: flex;*/
    /*justify-self: center;*/
    /*align-items: center;*/
    /*height: 50px;*/
    /*line-height: 50px;*/
    margin-bottom: 10px;
    /*padding-top: 12px;*/

    .top-left-search {
      flex-grow: 2
    }

    .top-right-num {
      flex-grow: 1;
    }
  }
  .ListData {
    .ListData-ul {
      background-color: white;
      // margin: 14px 10px;
      border-radius: 10px;
      padding: 14px;
      width: 93%;
      margin: 0 auto;
      margin-top: 18px;
      box-shadow: 0 0 12px #e3e3e3;
      .ListData-name {
        color: dodgerblue;
        text-decoration: underline;
        font-size: 18px;
        font-weight: 1000;
      }
      .ListData-XZQH {
        font-size: 14px;
        color: black;
        line-height: 30px;
        span {
          color: black;
        }
      }
      .ListData-FWNum {
        font-size: 14px;
        color: black;
        line-height: 30px;
        span {
          color: #aaa;
        }
      }
    }
  }
  .bottom {
    /*display: flex;*/
    /*align-items: center;*/
    /*justify-content: space-around;*/
    /*margin-top: 12px;*/
    /*padding: 0 10px;*/
    // padding: 6px;
  }
}
</style>
